<link rel="stylesheet" href="../../assets/iconfont/demo.css">
<template>
  <div style="width:100%;height:100%;display: flex;justify-content: center;align-items: center;">
    <div class="outerBox">

      <div class="onlineList"
           style="width: 15%;height: 100%;background-color: #F7F7F7;box-sizing: border-box; float: left;border-right: 2px solid rgba(190,188,188,0.85)">
        <div
            style="width: 100%;height: 40px;line-height:40px;text-align:center;border-bottom: 2px solid rgba(190,188,188,0.85);">
          在线人数: <el-tag type="success">{{ onlineUser.length }}</el-tag>
        </div>
        <el-scrollbar :style="{height: onlineListBoxHeight + 'px'}">
          <div class="onlineItem" v-for="item in onlineUser">
            <el-avatar style="width: 40px;height: 40px;margin: 5px 7px;" fit="fill" :src="item.avatar"/>
            <div style="height: 50px;line-height: 50px;">{{ item.username }}</div>
          </div>
        </el-scrollbar>
      </div>
      <div class="chatBox" style="width: 85%;height: 100%;float: left;">
        <div id="messageArea" style="width: 100%;height: 85%;overflow: hidden;">
          <div
              style="width: 100%;height: 40px;line-height:40px;text-align:center;border-bottom: 2px solid rgba(190,188,188,0.85);">
            聊天广场
          </div>

          <el-scrollbar ref="messageBoxScrollRef"
                        class="messageScroll"
                        :style="{ height: messageBoxHeight + 'px',paddingTop: '7px', boxSizing: 'border-box'}">
            <!--            渲染聊天-->
            <div id="messageOutBox">
              <div class="messageItem" v-for="item in messages" style="margin-bottom: 17px;overflow: hidden">
                <el-avatar class="messageAvatar" :style="{float: item.userId == curUserId ? 'right':'left'}" fit="fill"
                           :src="item.avatar"/>
                <div :style="{float: item.userId == curUserId ? 'right':'left'}">
                  <p :style="{textAlign: item.userId == curUserId ? 'right':'left', marginBottom: '4px'}">{{
                      item.username
                    }}
                    <el-tag v-if="item.userId == 7" style="margin:0 4px;" type="success">管理员</el-tag>
                  </p>
                  <p v-if="item.type == 0"
                     :style="{backgroundColor: item.userId == curUserId ? '#a5e858' :'#56BCF9', width:'auto',padding: '4px',borderRadius: '5px'}">
                    {{ item.content.trim() }}</p>
                  <el-image v-if="item.type == 1" :style="{float: item.userId == curUserId ? 'right':'left'}"
                            :src="item.content" class="messageImage"></el-image>
                </div>
              </div>
            </div>


            <div class="toBottom">
              <el-button type="success" :icon="Download" circle @click="setScrollToBottom"/>
            </div>
          </el-scrollbar>
        </div>
        <div class="messageInputBox"
             style="width: 100%;height: 15%;
             background-color: #fff;
             border-top: 2px solid rgba(190,188,188,0.85);
             display: flex;
             box-sizing: border-box">
          <div style="flex: 0.5;padding: 10px;display: flex;flex-direction: column;align-items: center;">
            <el-popover placement="top" trigger="click" width="400">
              <template #reference>
                <i class="iconfont icon">&#xe67b;</i>
              </template>
              <template #default>
                <EmojiPicker class="emojiBox"
                             hide-group-icons
                             hide-group-names
                             :native="true"
                           @select="selectEmoji"/>
              </template>
            </el-popover>


            <el-icon class="" style="color: #b0b0b0;">
              <FolderAdd/>
            </el-icon>


            <el-icon class="icon" @click="this.uploadImgDialogVisible = true">
              <PictureRounded/>
            </el-icon>
          </div>
          <div style="flex: 7;padding: 10px 0;">
            <el-input id="inputMessage" v-model="inputMessage" placeholder="请输入消息"
                      @keyup.enter="submitHandle"
                      style="width: 100%;height: 100%;"/>
          </div>
          <div style="flex: 1;padding: 10px">
            <el-button style="width: 100%;height: 100%;font-size: 18px;font-weight: bold" @click="submitHandle(0)">
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <el-dialog
      v-model="uploadImgDialogVisible"
      title="上传图片"
      width="30%"
  >
    <span>请选择要上传的图片</span>
    <el-divider style="margin: 10px 0"/>
    <el-upload
        ref="uploadImgRef"
        action="#"
        :limit="1"
        :on-exceed="exceedHandle"
        :before-upload="beforeUploadHandle"
        :auto-upload="false"
    >
      <template #trigger>
        <el-button :icon="DocumentAdd" type="primary" style="width: 100px;height: 30px;">选择图片</el-button>
      </template>
      <el-button :icon="Promotion" type="success" @click="submitUpload" style="margin-left: 5px;">
        确定发送
      </el-button>
      <template #tip>
        <div class="el-upload__tip text-red">
          只能选择一张图片
        </div>
      </template>
    </el-upload>
  </el-dialog>

</template>

<script>
import EmojiPicker from 'vue3-emoji-picker'
import 'vue3-emoji-picker/css'
import {Avatar, DocumentAdd, Download, FolderAdd, PictureRounded, Promotion, Star} from "@element-plus/icons-vue";
import request from "@/utils/request";


import '@/assets/iconfont/iconfont.css'
import {ElMessage} from "element-plus";


let client
export default {

  name: "Square",
  computed: {
    Promotion() {
      return Promotion
    },
    DocumentAdd() {
      return DocumentAdd
    },
    Download() {
      return Download
    },
    Star() {
      return Star
    }
  },
  components: {PictureRounded, FolderAdd, Avatar, EmojiPicker},
  data() {
    return {
      curUserId: '',
      messageBoxHeight: 0,
      onlineListBoxHeight: 0,
      inputMessage: '',
      onlineUser: [],
      messages: '',
      emojiVisible: false,
      uploadImgDialogVisible: false
    }
  },
  methods: {
    getCurUserId() {
      request.get('/getUserId').then(
          res => {
            this.curUserId = res.data
            console.log("curId:" + this.curUserId)
          },
          err => {
            console.log(err)
          }
      )
    },
    setScrollToBottom() {
      this.$nextTick(() => {
        const max = document.getElementById("messageOutBox").clientHeight
        console.log(document.getElementById("messageOutBox").clientHeight)
        console.log('max', max);
        this.$refs.messageBoxScrollRef.setScrollTop(max);
      })
    },
    submitHandle(type) {
      this.emojiVisible = false
      if (!this.inputMessage || /^\s*$/.test(this.inputMessage))
        ElMessage({
          message: "请输入信息",
          type: "error"
        })
      client.send(JSON.stringify({type: type, message: this.inputMessage}))
      this.inputMessage = ''
    },
    getHistoryMessages() {
      //   从数据库获取历史聊天
      request.get("/groupMessage/getAll").then(
          res => {
            this.messages = res.data
          },
          err => {
            console.log(err)
          }
      )
    },
    selectEmoji(emoji) {
      // console.log(emoji.i)
      let box = document.getElementById('inputMessage');
      // console.log(box.selectionStart)
      let pos = box.selectionStart
      let rawStr = this.inputMessage

      this.inputMessage = rawStr.slice(0, pos) + emoji.i + rawStr.slice(pos)
      box.selectionStart = pos + 1
      box.selectionEnd = pos + 1
    },
    beforeUploadHandle(file) {
      //   设置上传

      request.post("/uploadImage", {"file": file}, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      }).then(
          res => {
            console.log(res.data.resPath)
            //   关闭窗口，并通过websocket创建消息
            this.inputMessage = res.data.resPath
            this.submitHandle(1)
            this.uploadImgDialogVisible = false
          },
          err => {
            console.log(err)
          }
      )
    },
    submitUpload() {
      this.$refs.uploadImgRef.submit()
    },
    exceedHandle(files) {
      this.$refs.uploadImgRef.clearFiles()
      const file = files[0];
      this.$refs.uploadImgRef.handleStart(file);
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.messageBoxHeight = document.getElementById('messageArea').offsetHeight - 42;
      this.onlineListBoxHeight = document.getElementsByClassName('onlineList')[0].offsetHeight - 42;
      this.setScrollToBottom()
    })

    this.getCurUserId()
    this.getHistoryMessages()
    //   建立ws连接
    client = new WebSocket(localStorage.getItem("VUE_APP_WEBSOCKET_URL") + '/square/' + localStorage.getItem('jwt'))

    client.onmessage = (res) => {
      let msg = JSON.parse(res.data)
      if (msg.code == 101) {
        //   101 为用户列表信息
        this.onlineUser = msg.data
      }
      if (msg.code == 102) {
        //   102 为用户发送的新消息
        this.messages.push(msg.data)
        this.setScrollToBottom()
      }
    }

    client.onopen = () => {
      console.log("连接建立啦！")
    }

  },
  beforeDestroy() {
    // 手动关闭连接
    if (client)
      client.close()
  },
  beforeRouteLeave() {
    // 手动关闭连接
    if (client)
      client.close()
  }
}
</script>

<style scoped>

.icon {
  cursor: pointer;
  user-select: none;
  font-size: 17px;
}

.icon:hover {
  color: #bebebe;
}

.outerBox {
  width: 100%;
  height: 100%;
}

.onlineItem {
  transition: all .2s ease;
  height: 50px;
  line-height: 50px;
  display: flex;
}

.onlineItem:hover {
  background-color: #fff;
}

.messageAvatar {
  display: block;
  float: left;
  width: 40px;
  height: 40px;
  margin: 5px 7px;
}

.messageImage {
  width: 300px;
  display: block;
}

.messageScroll {
  position: relative;
}

.toBottom {
  position: absolute;
  bottom: 20px;
  right: 20px;
}

.emojiBox {
  width: 400px;
  sdisplay: block;
  position: absolute;
  left: 0;
  bottom: 5px;
  overflow: scroll;
}
</style>